<?php

namespace App\Factory\Sms;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class AliyunSmsSender implements SmsSenderInterface
{

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public function sendSMS($phoneNumber,$templateCode,$templateParam,$args=[],$debug=false) :bool{
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = $this->createClient(config('openapi')['ali_api_accessKey_id'], config('openapi')['ali_api_accessKey_secret']);
        if(!isset($args['signName'])){
             return false;
        }
        $sendSmsRequest = new SendSmsRequest([
            "signName" => $args['signName'],
            "templateCode" => $templateCode,
            "phoneNumbers" => $phoneNumber,
            "templateParam" => $templateParam
        ]);

        try {
            // 复制代码运行请自行打印 API 的返回值
            $r = $client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions([]));
            if($debug){
                dd($r);
            }
            if($r->body->code!='ok'){
                s_fail_return(null,$r->body->message);
            }
            return true;
        }
        catch (Exception $error) {
            if($debug){
                dd($error);
            }
            return false;
        }
    }
}
